<? // unique - whether table.login is unique

//-require_once '../ajax/dd.php';
$dd = unserialize(file_get_contents('../ajax/dd.ser'));

$args = $_GET['args'];

// breakout
foreach( $args as $pre=>$v ) break;

$rel   = @$args[$pre]['dd'];
$tbl   = @$args[$pre]['tbl'];
$pkcol = @$args[$pre]['pkcol'];

// if no dd, try pre
if( !$rel && $dd[$pre] ) $rel = $pre;

// tbl and pkcol
if( !$tbl && $rel ) $tbl = $dd[$rel]['tbl'];
if( !$pkcol && $rel ) $pkcol = $dd[$rel]['pkcol'];
if( !$tbl ) ajax_exit( 'failure', "no table or dictionary reference" );

// get row
foreach( $args[$pre]['rows'] as $idx=>$row ) break;
$key  = @$row['key'];
$pkid = @$row['pkid'];
if( !$key && $pkcol && $pkid ) $key = "$pkcol = $pkid";
//-ajax_exit( 'failure', "row: "+var_export($row) );

// get att
foreach( $row['cols'] as $att=>$attribute ) break;
$col = @$attribute['col'];
$val = @$attribute['value'];
if( !$col ) ajax_exit( 'failure', "attempting to get att.col" );
if( empty($col) ) ajax_exit( 'failure', "empty column value" );

$query = "select not exists( select 1 from $tbl where $col = '$val'".(($key)?" and not( $key )":'').' )';
$ok = db_get_col( $query );

// name of table and column
$tblNm = @$dd[$rel]['name'];
if( !$tblNm ) $tblNm = ucwords($tbl);
$colNm = @$dd[$rel]['cols'][$att]['label'];
if( !$colNm ) $colNm = ucwords($col);

if( $ok ) {
	ajax_exit( 'success', "$colNm = $val in $tblNm does not yet exist" );
}
else if( !$key ) {
	ajax_exit( 'failure', "$colNm = $val already in $tblNm" );
}
else {
	$old_val = db_get_col( "select $col from $tbl where $key" );
	ajax_exit( 'failure', "$colNm = $val already in $tblNm", Array('val'=>$old_val) );
}

?>
